package com.manor.main.activity;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.animation.SlideInBottomAnimation;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.manor.common.CommonAppConfig;
import com.manor.common.activity.AbsActivity;
import com.manor.common.bean.UserBean;
import com.manor.common.http.HttpCallback;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.dynamic.adapter.NewCirclePopAdapter;
import com.manor.im.activity.HChatRoomActivity;
import com.manor.main.R;
import com.manor.main.adapter.MainBottomSameCityAdapter;
import com.manor.main.bean.BottomSameCityBean;
import com.manor.main.http.MainHttpUtil;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.imsdk.v2.V2TIMConversation;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 搜索
 */
public class MainSearchActivity extends AbsActivity implements View.OnClickListener {
    RecyclerView mRecycleView;
    SmartRefreshLayout srlSeach;
    EditText mEtInputUser;
    RecyclerView rv_list;
    TextView tv_qk;

    private LinearLayoutManager mLayoutManager;
    MainBottomSameCityAdapter mainBottomSameCityAdapter;
    private List<BottomSameCityBean> bottomSameCityBeanList = new ArrayList<>();


    private int pageNum = 1;
    private UserBean mUserBean;
    private TextView mIvBack;
    private ArrayList<String> list = new ArrayList<>();
    private FrameLayout cardview;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_seach;
    }

    @Override
    protected void main() {
        super.main();
        initView();
        initDate();
    }

    private void initDate() {
        srlSeach.setEnableLoadMore(false);
        srlSeach.setEnableRefresh(false);
        srlSeach.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (StringUtil.isNotEmpty(mEtInputUser.getText().toString())) {
                    pageNum++;
                    setDate(pageNum, getKeyword());
                } else {
                    ToastUtil.show("输入淘米号或者昵称");
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (StringUtil.isNotEmpty(mEtInputUser.getText().toString())) {
                    pageNum = 1;
                    setDate(pageNum, getKeyword());
                } else {
                    ToastUtil.show("输入淘米号或者昵称");
                }
            }
        });

        mEtInputUser.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            seachUser(mEtInputUser.getText().toString());
                            if(mEtInputUser.getText().equals("")){
                                return false;
                            }
                            list.clear();
                            list.add(mEtInputUser.getText() + "");
                            getSearchList();
                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                                List newList = list.stream().distinct().collect(Collectors.toList());
                                String s = new Gson().toJson(newList);
                                CommonAppConfig.getInstance().setSearch(s);
                            }else {
                                for (int i = 0; i < list.size(); i++) {
                                    for (int j = 0; j < list.size(); j++) {
                                        if(i!=j&&list.get(i)==list.get(j)) {
                                            list.remove(list.get(j));
                                        }
                                    }
                                }
                                String s = new Gson().toJson(list);
                                CommonAppConfig.getInstance().setSearch(s);
                            }

                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        mainBottomSameCityAdapter.addChildClickViewIds(R.id.tv_send_msg);
        mainBottomSameCityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String id = bottomSameCityBeanList.get(position).getId();
                if (StringUtil.isNotEmpty(id)) {
                    UserCenterActivity.Companion.forward(MainSearchActivity.this, id);
                }
            }
        });

        mainBottomSameCityAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //获取这个用户的信息，然后跳转去聊天
                if (!"".equals(bottomSameCityBeanList.get(position).getId())) {
                    if (ClickUtil.canClick()) {

                        BottomSameCityBean it = bottomSameCityBeanList.get(position);
                        mUserBean = new UserBean();
                        mUserBean.setUserNiceName(it.getUser_nickname());
                        mUserBean.setFollows(1);
                        mUserBean.setId(it.getId());
                        if (!"".equals(it.getAvatar())) {
                            mUserBean.setAvatar(it.getAvatar());
                            mUserBean.setAvatarThumb(it.getAvatar());
                        }
//                        if (!"".equals(it.getThumb())) {
//                            mUserBean.setAvatarThumb(it.getThumb());
//                        }
                        //跳转去聊天
//                        ChatRoomActivity.forward(MainSearchActivity.this, mUserBean, mUserBean.isFollowing(), mUserBean.isBlacking(), true, false);

                        HChatRoomActivity.Companion.forward(mContext,it.getId(),it.getUser_nickname(),
                                StringUtil.isNotEmpty(it.getAvatar())?it.getAvatar():"",
                                V2TIMConversation.V2TIM_C2C);
                    }
                }
            }
        });

    }

    /**
     * 搜索用户
     *
     * @param userInfo
     */
    private void seachUser(String userInfo) {
        if (StringUtil.isNotEmpty(userInfo)) {
            rv_list.setVisibility(View.GONE);
            tv_qk.setVisibility(View.GONE);
            cardview.setVisibility(View.VISIBLE);
            pageNum = 1;
            setDate(pageNum, userInfo);
        } else {
            ToastUtil.show("请输入用户昵称或淘米号再搜索");
        }

    }

    @NotNull
    private String getKeyword(){
        return mEtInputUser.getText().toString();
    }


    private void setDate(int pageNum, String keyword) {
        MainHttpUtil.getHomeSearch(pageNum, keyword, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0) {
                    if (StringUtil.isNotEmpty(info)) {
                        if (pageNum > 1) {
                            List<BottomSameCityBean> mList = JSON.parseArray(info, BottomSameCityBean.class);

                            bottomSameCityBeanList.addAll(mList);
                            srlSeach.finishLoadMore();
                        } else {
                            if (bottomSameCityBeanList.size() > 0) {
                                bottomSameCityBeanList.clear();
                            }
                            List<BottomSameCityBean> mList = JSON.parseArray(info, BottomSameCityBean.class);
                            bottomSameCityBeanList.addAll(mList);
                            srlSeach.finishRefresh();
                        }
                        srlSeach.setEnableLoadMore(true);
                        srlSeach.setEnableRefresh(true);
                        mainBottomSameCityAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtil.show("未找到相关内容");
                        srlSeach.finishLoadMore();
                        srlSeach.finishRefresh();
                        srlSeach.finishLoadMoreWithNoMoreData();
                    }
                } else {
                    srlSeach.finishLoadMore();
                    srlSeach.finishRefresh();
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onError() {
                super.onError();
                srlSeach.finishLoadMore();
                srlSeach.finishRefresh();
            }
        });


    }
    private NewCirclePopAdapter mAdapter;

    private void initView() {
        mRecycleView = findViewById(R.id.recycler_view);
        mEtInputUser = findViewById(R.id.et_input_user);
        srlSeach = findViewById(R.id.srl_seach);
        cardview = findViewById(R.id.cardview);
        rv_list = findViewById(R.id.rv_list);
        tv_qk = findViewById(R.id.tv_qk);
        tv_qk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonAppConfig.getInstance().setSearch("");
                list.clear();
                mAdapter.setNewInstance(list);
                mAdapter.notifyDataSetChanged();
            }
        });
                mLayoutManager = new LinearLayoutManager(MainSearchActivity.this);
        mRecycleView.setLayoutManager(mLayoutManager);
        mLayoutManager = new LinearLayoutManager(MainSearchActivity.this);
        rv_list.setLayoutManager(mLayoutManager);



//        mCityAdapter.setEmptyView(R.layout.view_no_data_common, mRecycleView);
        mainBottomSameCityAdapter = new MainBottomSameCityAdapter(R.layout.rv_mainsamecity_item, bottomSameCityBeanList);
        mainBottomSameCityAdapter.getLoadMoreModule().setEnableLoadMore(true);
        mainBottomSameCityAdapter.setAnimationEnable(true);
        mainBottomSameCityAdapter.setAdapterAnimation(new SlideInBottomAnimation());
        mRecycleView.setAdapter(mainBottomSameCityAdapter);


        mIvBack = findViewById(R.id.iv_back);

        mIvBack.setOnClickListener(this);
        mAdapter = new NewCirclePopAdapter(R.layout.rv_search_item, null);
        rv_list.setAdapter(mAdapter);
        getSearchList();
        mAdapter.setNewInstance(list);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                seachUser(list.get(position));
                mEtInputUser.setText(list.get(position));
            }
        });
    }
    private  void getSearchList(){
        String ss = (String) CommonAppConfig.getInstance().getSearch();//取值
        JSONArray param = null;
        try {
            if (ss.equals("")) {
                return;
            }
            param = new JSONArray(ss);
            String[] IDList = new String[param.length()];
            for (int i = 0; i < param.length(); i++) {
                IDList[i] = param.get(i).toString();
                list.add(param.get(i).toString());
            }


        } catch (JSONException e) {
            e.printStackTrace();

        }
    }


    public static void forward(Context context) {
        Intent intent = new Intent(context, MainSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            onBackPressed();
        }
//        else if (id == R.id.iv_search_user) {
//            seachUser(mEtInputUser.getText().toString());
//        }
    }
}
